package controller;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import entity.User;
import lombok.SneakyThrows;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * Author：汤小洋
 * Date：2023-12-15 10:45
 * Description：<描述>
 */
@Controller
public class HelloController {

    @RequestMapping("/hello")
    public ModelAndView hello(){
        System.out.println("HelloController.hello................");

        ModelAndView mav = new ModelAndView();
        mav.addObject("name","张三"); // 数据是存放到request作用域中
        mav.setViewName("hello"); // 会自动拼接前缀和后缀    /view/hello.jsp
        return mav;
    }

    @RequestMapping("/hello2")
    public String hello2(Model model){ // 将数据存放到Model中
        System.out.println("HelloController.hello2..............");

        model.addAttribute("name", "李四");
        // return "hello"; // 转发到视图
        // return "forward:hello"; // 转发到控制器/hello
        return "redirect:hello"; // 重定向到控制器/hello
    }

    @SneakyThrows
    @RequestMapping("/hello3")
    public void hello3(HttpServletResponse response) {
        System.out.println("HelloController.hello3................");

        response.setContentType("application/json;charset=utf8");
        PrintWriter out = response.getWriter();
        User user = new User(1, "tom", "123", 18, 190.78, new Date());
        out.print(JSONUtil.toJsonStr(user));
        out.close();
    }
}
